import React, { Component, PropTypes } from 'react'
import {currencyPrecisionCal, invoiceAmountChange, messages, queryCurrencyPrecision} from "share/common";
import {Popover} from "antd";
import constants from "share/constants";
import {ExpandIcon, wrappedExpandAllRow} from "components/table/table-expand-all";
import Echarts from "components/echarts";
import Table from "components/table";
import antdc from "share/prototype-extend/antd-common";
import Invoice from "containers/my-account/invoice";
import expenseReportFunction from 'containers/expense-report/expense-report.function'

const { invoiceColumnsCompare } = expenseReportFunction;
const { renderPopover } = antdc;

class SlideExpenseReportDetailExpenseListTable extends Component {
  state = {
    expandedAll: false,
    expandedRowKeys: [],
    columns: [{
      title: messages('common.sequence')/*序号*/, dataIndex: 'index', width: 72,
      render: (value, record, index) => index + 1,
      className: 'table-row-right-align'
    }, {
      title: messages('common.expense.type')/*费用类型*/,
      dataIndex: 'expenseTypeName',
      width: 150,
      sorter: (a, b) => a.expenseTypeName.localeCompare(b.expenseTypeName, 'zh-Hans-CN', { sensitivity: 'accent' }),
      render: (value, record) => (
        <Popover content={value}>
          <img src={record.expenseTypeIconURL} className='slide-expense-report-detail-expense-list-table-type-icon' />
          {value}
        </Popover>
      )
    }, {
      title: messages('common.date')/*日期*/,
      dataIndex: 'createdDate',
      width: 100,
      render: value => new Date(value).format('yyyy-MM-dd'),
      sorter: (a, b) => new Date(a.createdDate) - new Date(b.createdDate)
    }, {
      title: messages('common.currency')/*币种*/,
      dataIndex: 'invoiceCurrencyCode',
      width: 48
    }, {
      title: messages('common.amount')/*金额*/,
      dataIndex: 'amount',
      align: 'right',
      width: 100,
      sorter: (a, b) => a.amount - b.amount,
      render: (value, record) => {
        let precision1 = currencyPrecisionCal(record.invoiceCurrencyCode, record.amount);
        let precision2 = currencyPrecisionCal(record.invoiceCurrencyCode, record.originalAmount);
        let param1 = precision1 !== precision2 || record.actualCurrencyRate !== record.originalActualCurrencyRate;
        let showText = invoiceAmountChange(param1, value || record.amount, record.invoiceCurrencyCode);
        return renderPopover(showText)
      }
    }, {
      title: messages('common.matter')/*事由说明*/,
      dataIndex: 'comment',
      width: 100,
      render: value => renderPopover(value)
    }]
  };

  getMessageKeyColumns(key, messageKey, config) {
    return {
      title: config.title,
      width: config.width || 100,
      dataIndex: key,
      messageKey,
      render: (text, expense) => {
        let field = expense.data.find(item => item.newMessageKey === key);
        return renderPopover(field && config.render(field));
      }
    }
  }

  renderInvoiceExpanded = record => {
    let result = [];
    if(record.summaryInfo) {
      result.push(
        <div className='slide-expense-report-detail-expense-list-table-summary' key='summaryInfo'>
          {record.summaryInfo.replace(/&#13;/g, ' ')}
        </div>
      )
    }
    const infoList = [];
    record.invoiceLabels.map(label => {
      if(label.level === 'INFO') {
        infoList.push(label.name);
      } else {
        let className = label.level === 'WARN' ? 'warning-expanded-row' : (label.level === 'ERROR' ? 'error-expand-row' : '');
        let content = <div>
          {label.name}
          {label.toast && label.toast.split('&#13;').map((item, index) => {
            if (index === 0)
              return <span>：{item}</span>;
            return <div>{item}</div>
          })}
        </div>;
        if(label.name) {
          result.push(
            <div className={`expanded-row-list ${className}`} key={`type-${result.length}`}>
              {renderPopover(content)}
            </div>
          )
        }
      }
    });
    if(infoList.length > 0) {
      let content = infoList.join('/');
      result.push(
        <div className="expanded-row-list" key={`type-${result.length}`}>
          {renderPopover(content)}
        </div>
      )
    }
    record.receiptList.map((invoice, index) => {
      result.push(
        <div className='slide-expense-report-detail-expense-list-table-invoice' key={`invoice-${index}`}>
          <Invoice invoiceList={[invoice]} disabledEdit/>
        </div>
      )
    });
    return result.length === 0 ? null : <div className='slide-expense-report-detail-expense-list-table-row'>{result}</div>;
  };

  getColumns = () => {
    const { group } = this.props;
    let { columns } = this.state;
    let insertedColumns = [];
    columns.map(item => insertedColumns.push(item.dataIndex));
    group.invoices.map(invoice => {
      invoice.invoiceView.data.map(field => {
        let { messageKey, fieldOID } = field;
        let target = constants.targetMessageKeys[messageKey];
        let messageKeyIndex = messageKey && invoice.invoiceView.data
          .filter(i => i.messageKey === messageKey)
          .findIndex(i => i.fieldOID === fieldOID);
        messageKey && (messageKey += messageKeyIndex);
        if (target && !insertedColumns.includes(messageKey) && field.showOnList) {
          insertedColumns.push(messageKey);
          columns.push(this.getMessageKeyColumns(messageKey, field.messageKey, target));
        }
      })
    });
    columns.map(item => {
      let { messageKey, dataIndex } = item;
      let messageKeyColumns = messageKey && columns.filter(i => i.messageKey === messageKey);
      if (messageKeyColumns && messageKeyColumns.length > 1) {
        let itemIndex = messageKeyColumns.findIndex(i => i.dataIndex === dataIndex);
        item.title = `${item.title}${itemIndex + 1}`;
      }
    });
    columns.map(item => item.messageKey && delete item.messageKey);
    return columns;
  };

  renderRowClass = record => {
    const { isWaitForAudit } = this.context;
    let classNames = [];
    !this.renderInvoiceExpanded(record) && classNames.push('row-expand-display-none');
    isWaitForAudit && record.manualAudit && classNames.push('invoice-has-audit');
    return classNames.length ? classNames.join(' ') : '';
  };

  formatDataSource = data => {
    const { filterExpense, filterExpenseByCalendarMode, sorter } = this.props;
    let dataSource = data
      .filter(filterExpense)
      .filter(filterExpenseByCalendarMode)
      .map(invoice => invoice.invoiceView)
      .sort(invoiceColumnsCompare(sorter.columnKey, sorter.order));
    dataSource.map(invoice => {
      invoice.data.map(field => {
        let { messageKey, fieldOID } = field;
        let messageKeyIndex = messageKey && invoice.data
          .filter(i => i.messageKey === messageKey)
          .findIndex(i => i.fieldOID === fieldOID);
        messageKey && (messageKey += messageKeyIndex);
        field.newMessageKey = messageKey;
      })
    });
    return dataSource;
  };

  render() {
    const { expenseReportInvoices, rowSelection, group,
      onOpenExpenseDetail, onClickCollapse, tableLoading, showEmpty } = this.props;
    const { info, isWaitForAudit } = this.context;
    const { expandedAll, expandedRowKeys } = this.state;
    let columns = this.getColumns();
    let dataSource = this.formatDataSource(group.invoices);
    let allMoney = expenseReportInvoices.reduce((pre, now) => now.invoiceView.baseAmount + pre, 0);
    let groupMoney = dataSource.reduce((pre, now) => now.baseAmount + pre, 0);
    let { showIcon, onExpand, onExpandAllRows } = wrappedExpandAllRow(
      {
        dataSource,
        expandedAll,
        expandedRowKeys,
        rowKey: 'invoiceOID',
        expandedRowRender: this.renderInvoiceExpanded,
      }, params => this.setState(params));
    return (dataSource.length > 0 || showEmpty) ? (
      <div>
        <div className='slide-expense-report-detail-expense-list-title'>
          {group.categoryName}
          <Echarts
            className='slide-expense-report-detail-expense-list-title-chart'
            width={34}
            height={34}
            options={{
              color: ['rgba(176, 212, 251, .5)'],
              series: [{
                type: 'pie',
                clockWise: true,
                radius: ['33%', '50%'],
                itemStyle: {
                  normal: {
                    label: {
                      show: false
                    },
                    labelLine: {
                      show: false
                    }
                  }
                },
                hoverAnimation: false,
                data: [{
                  value: groupMoney,
                  itemStyle: {
                    normal: {
                      color: {
                        colorStops: [{
                          offset: 0,
                          color: '#00cefc'
                        }, {
                          offset: 1,
                          color: '#367bec'
                        }]
                      },
                      label: {
                        show: false
                      },
                      labelLine: {
                        show: false
                      }
                    }
                  }
                }, {
                  value: allMoney - groupMoney
                }]
              }]
            }}
          />
          {(allMoney ? groupMoney / allMoney * 100 : 100).toFixed(2)}%
          <span className="ant-divider"/>
          {messages('common.number')/*数量*/}: {dataSource.length}
          <span className="ant-divider"/>
          <span className='slide-expense-report-detail-expense-list-title-money'>
            {messages('common.total.amount')/*总金额*/}: {info.baseCurrency}&nbsp;
            {
              this.filterMoney(
                groupMoney,
                queryCurrencyPrecision(info.baseCurrency)
              )
            }
          </span>
        </div>
        <div className='slide-expense-report-detail-expense-list-container'>
          <ExpandIcon onExpandAllRows={onExpandAllRows} expandedAll={expandedAll} showIcon={showIcon}/>
          <Table
            loading={tableLoading}
            className='slide-expense-report-detail-expense-list-table'
            columns={columns}
            dataSource={dataSource}
            rowKey='invoiceOID'
            showUtils
            tableName='new-audit-expense-account-table'
            pagination={false}
            expandedRowRender={this.renderInvoiceExpanded}
            rowClassName={this.renderRowClass}
            rowSelection={isWaitForAudit ? rowSelection : void 0}
            scroll={{x:  true}}
            expandedRowKeys={expandedRowKeys}
            onExpand={onExpand}
            onRow={nowExpense => ({
              onClick: () => onOpenExpenseDetail(nowExpense, dataSource)
            })}
            onRef={tableRef => onClickCollapse({tableRef, columns})}
            onSort={columns => this.setState({ columns })}
            onResize={columns => this.setState({ columns })}
            onHide={columns => setTimeout(() => this.setState({ columns }), 0)}
            onChange={this.props.onChange}
          />
        </div>
      </div>
    ) : null
  };

  static contextTypes = {
    info: PropTypes.object,
    isWaitForAudit: PropTypes.bool,
    isAuditEditable:  PropTypes.bool,
    isSupportSingleReject: PropTypes.bool
  };
}

export default SlideExpenseReportDetailExpenseListTable
